package com.linkwedo.saas.member;

import java.util.Map;

import javax.naming.NameNotFoundException;
import javax.naming.NamingException;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.linkwedo.saas.datasource.ConnectionInfo;
import com.linkwedo.saas.datasource.ConnectionStrategy;
import com.linkwedo.saas.directory.JNDIService;
import com.linkwedo.saas.directory.LDAPService;
import com.linkwedo.saas.domain.member.User;
import com.linkwedo.saas.support.Constants;
import com.linkwedo.saas.support.JNDIURLList;

public class LoginService {
	/**
	 * 获取连接信息，并在必要时将数据源放置于JNDI中
	 * @param  
	 * 
	 * @param companyRDN
	 * @param application
	 * @param session
	 * @throws NamingException
	 */
	public static void doLoginWork(String email,
			String userDN, Map<String, Object> application, Map<String, Object> session)
			throws NamingException {
		Object user = null;
		synchronized (session) {
			user = session.get(Constants.USER);
		}
		if (user == null) {
			// 获取公司dn
			String companyRDN = LDAPService.getCompanyRDN(userDN);

			// 获取连接信息
			ConnectionInfo connectionInfo = LDAPService
					.getConnectionInfo(companyRDN);

			String jndiURL = connectionInfo.getJndiURL();
			BasicDataSource dynamicDataSource = null;
			try {
				dynamicDataSource = JNDIService.getDataSource(jndiURL);
			} catch (NamingException e) {
				//if (e.getCause() instanceof NameNotFoundException) {
					synchronized (application) {
						if (!JNDIURLList.isAdded(jndiURL, application)) {
							ApplicationContext datasourceContext = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletActionContext.getServletContext());
							dynamicDataSource = (BasicDataSource) datasourceContext
									.getBean("dynamicDataSource");
							ConnectionStrategy.reConfigDataSource(
									connectionInfo, dynamicDataSource);
							JNDIService.bindDataSource(jndiURL,
									dynamicDataSource);
							JNDIURLList.add(jndiURL, application);
						}
					}
				//} else {
				//	throw e;
				//}
			}

			User newUser = new User();
			newUser.setEmail(email);
			synchronized (session) {
				session.put(Constants.USER, newUser);
				session.put(Constants.JNDIURLKEY, jndiURL);
			}
			ThreadLocalJNDIURL.putJNDIURL(jndiURL);
		}
	}
}
